import Vue from "vue";
import Vuex from "vuex";

import dynamicRouters from "../router/dynamicRouters"
import allRouters  from "../router/allRouters" 
import recursionRouters from "../utils/recursionRouters"
import * as api from "../api"
import router from "../router";


Vue.use(Vuex);



let userInfo =localStorage.getItem("app-userInfo")  || "{}";
export default new Vuex.Store({
  state: {
    userInfo:JSON.parse(userInfo),
    sideMenu:[] ,//用户侧边栏菜单,
    menuCollapse: false,//控制侧边菜单的收起和展开
    breadCrumb:[] , //用来存储面包屑的数据
  },
  mutations: {
    //这里是更改state的唯一方式
    setUserInfo(state,payload){
      state.userInfo=payload
    },
    SET_MENU_COLLAPSE(state) {
      state.menuCollapse = !state.menuCollapse
    },
    SET_SIDEMENU(state,payload){
      state.sideMenu=[...payload]
      // 设置dynamicRouters=>将用户路由添加到当前数组中的path="/"的对象的children属性中
      //添加完成之后，还需要将整个dynamicRouters通过addRoutes的方式添加到系统路由routes中
      let target =dynamicRouters.find(item=>item.path==="/")
      target.children=[...payload]

      // 将dynamicRouters动态添加到路由中
      // console.log(dynamicRouters);
      router.addRoutes(dynamicRouters)
    },
    SET_BREADCRUMB(state,payload){
      state.breadCrumb=payload
    }

  },
  actions: {
    //发起异步请求，获取用户菜单
    FETCH_MENU_LIST({commit}){
      //发送请求获取用户菜单
    return  api.getMenuLisyApi()
        .then(res=>{
          // console.log(res);
          let menuList =res.data.menuList
          // console.log(menuList);
          //递归匹配出用户路由
          let userMenu =recursionRouters(allRouters,menuList);
          commit("SET_SIDEMENU",userMenu)

        })
    }
  },
  modules: {},
});
